﻿// Manages the z-index of the views subscribed to it
define([
    'Wjs/Wjs'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'zIndexManager',

        internal: {

            'static': true,

            construct: function () {

                this.views = []; // The managed views

                this.initialValue = 1000;
                this.increment = 10;
            }
        },

        // Add a displayed popup view to manage its z-index by this manager
        add: function (view) {
            var zIndex = this.getMaxZIndex();

            if (zIndex < this.initialValue) {

                zIndex = this.initialValue
            }
            else {

                zIndex += this.increment;
            }

            view.setStyleProperty('z-index', zIndex);

            this.views.push(view);
        },

        remove: function (view) {

            this.views.forEach(function (v, i) {

                if (v === view) {

                    this.views.splice(i, 1);
                }
            },
            this);
        },

        // Retrieves the biggest z-index from the views being managed
        getMaxZIndex: function () {
            var maxZIndex = 0,
                zIndex = 0;

            this.views.forEach(function (v, i) {

                zIndex = parseFloat(v.getStyleProperty('z-index'));

                if (zIndex > maxZIndex) { // No need to test for null or undefined
                    maxZIndex = zIndex;
                }
            });

            return maxZIndex;
        }
        
    });

});